// 更新PDF转换状态
const { Pool } = require('pg');
const fs = require('fs');
const path = require('path');

// 数据库连接配置
const pool = new Pool({
  host: '118.178.138.0',
  port: 9070,
  database: 'postgres',
  user: 'postgres',
  password: 'difyai123456',
  max: 20,
  idleTimeoutMillis: 90900,
  connectionTimeoutMillis: 2000,
});

async function updatePdfStatus() {
  try {
    console.log('🔄 更新PDF转换状态...\n');
    
    // 查询所有PDF转换记录
    const pdfQuery = `
      SELECT pc.*, mf.original_name, mf.file_name, mf.mime_type
      FROM pdf_conversions pc
      JOIN media_files mf ON pc.original_file_id = mf.id
      ORDER BY pc.created_at DESC
    `;
    
    const pdfResult = await pool.query(pdfQuery);
    console.log(`📋 找到${pdfResult.rows.length}条PDF转换记录\n`);
    
    let updatedCount = 0;
    
    for (const record of pdfResult.rows) {
      console.log(`处理记录: ${record.original_name} (ID: ${record.id})`);
      console.log(`  当前状态: ${record.conversion_status}`);
      
      if (record.mime_type === 'application/pdf') {
        // PDF文件，检查原文件是否存在
        const originalFilePath = path.join(process.cwd(), 'uploads', record.file_name);
        
        if (fs.existsSync(originalFilePath)) {
          // 更新为completed状态，使用原文件作为PDF
          const updateQuery = `
            UPDATE pdf_conversions 
            SET conversion_status = 'completed', 
                pdf_url = $1, 
                pdf_path = $2,
                updated_at = CURRENT_TIMESTAMP
            WHERE id = $3
          `;
          
          await pool.query(updateQuery, [
            `/uploads/${record.file_name}`,
            originalFilePath,
            record.id
          ]);
          
          console.log(`  ✅ 更新为completed状态`);
          updatedCount++;
        } else {
          console.log(`  ❌ 原文件不存在，保持failed状态`);
        }
      } else {
        // Office文档，检查是否需要转换
        const originalFilePath = path.join(process.cwd(), 'uploads', record.file_name);
        
        if (fs.existsSync(originalFilePath)) {
          // 文件存在，可以标记为processing等待转换
          const updateQuery = `
            UPDATE pdf_conversions 
            SET conversion_status = 'processing',
                updated_at = CURRENT_TIMESTAMP
            WHERE id = $1
          `;
          
          await pool.query(updateQuery, [record.id]);
          console.log(`  🔄 更新为processing状态，等待转换`);
          updatedCount++;
        } else {
          console.log(`  ❌ 原文件不存在，保持failed状态`);
        }
      }
    }
    
    console.log(`\n📊 更新结果:`);
    console.log(`  - 更新记录数: ${updatedCount}`);
    
    // 显示最新的PDF转换记录统计
    const statsQuery = `
      SELECT conversion_status, COUNT(*) as count
      FROM pdf_conversions
      GROUP BY conversion_status
      ORDER BY conversion_status
    `;
    
    const statsResult = await pool.query(statsQuery);
    console.log(`\n📈 PDF转换记录统计:`);
    statsResult.rows.forEach(row => {
      console.log(`  - ${row.conversion_status}: ${row.count}条`);
    });
    
    // 显示详细记录
    const detailQuery = `
      SELECT pc.id, mf.original_name, pc.conversion_status, pc.pdf_url
      FROM pdf_conversions pc
      JOIN media_files mf ON pc.original_file_id = mf.id
      ORDER BY pc.updated_at DESC
    `;
    
    const detailResult = await pool.query(detailQuery);
    console.log(`\n📝 详细记录:`);
    detailResult.rows.forEach((row, index) => {
      console.log(`  ${index + 1}. ${row.original_name} - ${row.conversion_status} - ${row.pdf_url || '无PDF'}`);
    });
    
    console.log('\n✅ 更新完成！');
    
  } catch (error) {
    console.error('❌ 更新失败:', error);
  } finally {
    await pool.end();
  }
}

// 运行更新
if (require.main === module) {
  updatePdfStatus();
}

module.exports = { updatePdfStatus };